﻿using System;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using ImageResizer;
using MSAcademic.v2.Infrastructure.Utility;

namespace MSAcademic.v2.Infrastructure.Picture.Impl
{
    public partial class PictureService : IPictureService
    {
        public void UserProfilePictureUpload(int userId,HttpPostedFileBase userPicture)
        {
            var path = FilePath + "Users/" + userId;
            if(!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory +path))
            {
                Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + path);
            }
            if(userPicture!=null)
            {
                var pictureByteArray = ToByteArray(userPicture);
                var pictureWidth = ConfigurationManager.AppSettings["UserProfilePictureDefaultWidth"];

                var resizeQuerystring = @"?W=" + pictureWidth + "&Mode=Stretch&Scale=Both";
                var resizedPicture = ResizePicture(pictureByteArray, resizeQuerystring);

                path += @"/" +resizedPicture.Length+ userPicture.FileName;
                File.WriteAllBytes(Path.Combine(HttpContext.Current.Server.MapPath("~/"),path),resizedPicture);

                _pictureCommands.SetUserProfilePicture(userId,path);

            }
        }
        public void ArticleFrontPictureUpload(int articleId,HttpPostedFileBase frontPicture)
        {
            var path = FilePath  + @"Articles/" + articleId.ToString(CultureInfo.InvariantCulture);
            if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + path))
            {
                Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + path);
            }
            if (frontPicture != null)
            {
                var pictureByteArray = ToByteArray(frontPicture);
                var pictureWidth = ConfigurationManager.AppSettings["ArticleFrontPictureDefaultMaxWidth"];
                var resizeQuerystring = @"?W="+pictureWidth+"&Mode=Stretch&Scale=Both";
                var resizedPicture = ResizePicture(pictureByteArray,resizeQuerystring);

                path += @"/" + pictureByteArray.Length.ToString(CultureInfo.InvariantCulture) + "-" +
                    frontPicture.FileName;

                File.WriteAllBytes(Path.Combine(HttpContext.Current.Server.MapPath(@"~/"), path), resizedPicture);

                _pictureCommands.SetArticleThumbnailPictureUrl(articleId,path);
                _pictureCommands.SetArticleNormalPictureUrl(articleId, path);
                _pictureCommands.SetArticleBigPictureUrl(articleId, path);
            }
            
        }
        public string GalleryPictureUpload(HttpPostedFileBase picture, int galleryId)
        {
            var path = FilePath + "Galleries/" + galleryId.ToString(CultureInfo.InvariantCulture);
            if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + path))
            {
                Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + path);
            }

            var pictureByteArray = ToByteArray(picture);
            var resizeQuerystring= @"?MaxWidth="+ConfigurationManager.AppSettings["ArticleGalleryPictureMaxWidth"]+"&MaxHeight="+ConfigurationManager.AppSettings["ArticleGalleryPictureMaxHeight"];
            var resizedPicture = ResizePicture(pictureByteArray, resizeQuerystring);

            path += @"/" + pictureByteArray.Length.ToString(CultureInfo.InvariantCulture) + "-" + picture.FileName;

            if (File.Exists(Path.Combine(HttpContext.Current.Server.MapPath(@"~/"), path)))
            {
                var fileName = Path.GetFileName(path);
                if (fileName != null)
                {
                    var newPicName = fileName.Replace(Path.GetFileNameWithoutExtension(path),
                                                      Path.GetFileNameWithoutExtension(path) +
                                                      RandomPictureIdentifier(4));

                    path = FilePath + "Galleries/" + galleryId.ToString(CultureInfo.InvariantCulture) +
                           @"/" + newPicName.ToLower();
                }
            }
            File.WriteAllBytes(Path.Combine(HttpContext.Current.Server.MapPath(@"~/"), path), resizedPicture);
            return path;

        }
        public string DownloadAndUploadPictureToGallery(string url,int galleryId)
        {
            var path = FilePath + "Galleries/" + galleryId.ToString(CultureInfo.InvariantCulture);
            var resizeQuerystring = @"?MaxWidth=" + ConfigurationManager.AppSettings["ArticleGalleryPictureMaxWidth"] + "&MaxHeight=" + ConfigurationManager.AppSettings["ArticleGalleryPictureMaxHeight"];

            if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + path))
            {
                Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + path);
            }

            var client = new WebClient();
            var pic = client.DownloadData(new Uri(url));
            if (pic.Length > 0)
            {
                var resizedPicture = ResizePicture(pic, resizeQuerystring);
                path += @"/" +
                        _randomNonceGenerator.GetNewWithoutSpecialChars(
                            Convert.ToInt32(ConfigurationManager.AppSettings["GalleryPictureNameLegth"])) +
                        RandomPictureIdentifier(3) + Path.GetExtension(url);

                File.WriteAllBytes(Path.Combine(HttpContext.Current.Server.MapPath(@"~/"), path), resizedPicture);
                return path;
            }
            return "-1";
        }
        public string DownloadAndUploadUserProfilePicture(string url,int userId)
        {
            var path = FilePath + "Users/" + userId;
            if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + path))
            {
                Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + path);
            }

            var client = new WebClient();
            var picture = client.DownloadData(new Uri(url));
            if(picture.Length>0)
            {
              var resizeQuerystring = @"?W=" + ConfigurationManager.AppSettings["UserProfilePictureDefaultWidth"] + "&Mode=Stretch&Scale=Both";
              var resizedPicture = ResizePicture(picture, resizeQuerystring);
              path += resizedPicture.Length + RandomPictureIdentifier(10)+Path.GetExtension(url);
              File.WriteAllBytes(Path.Combine(HttpContext.Current.Server.MapPath("~/"), path), resizedPicture);
             _pictureCommands.SetUserProfilePicture(userId,path);
              return path;

            }
            return "-1";

        }
    }
    public partial class PictureService
    {
        public byte[] ToByteArray(HttpPostedFileBase picture)
        {
            var pictureByteArray = new byte[picture.ContentLength];
            picture.InputStream.Read(pictureByteArray, 0, picture.ContentLength);
            return pictureByteArray;
        }
        public byte[] ResizePicture(byte[] pictureByteArray,string resizeQuerystring)
        {
            using (var outputStream = new MemoryStream())
            {
                using (var inputStream = new MemoryStream(pictureByteArray))
                {
                    var settings = new ResizeSettings(resizeQuerystring);
                    ImageBuilder.Current.Build(inputStream, outputStream, settings);
                    return outputStream.ToArray();
                }
            }

        }
        public string GetOriginalPictureUrl(string path)
        {
            path = path.Replace("cropedthumbnail", "").Replace("cropednormal", "").Replace("cropedbig", "").Replace("gallerycroped", "").Replace("profilecroped","");
            return path;
        }
        private string RandomPictureIdentifier(int size)
        {
            var builder = new StringBuilder();
            for (var i = 0; i < size; i++)
            {
                var ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * Random.NextDouble() + 65)));
                builder.Append(ch);
            }

            return builder.ToString();
        }
        public void SaveCroppedPicture(string pictureName, string pictureQuerystringUrl, string originalUrl)
        {

            var destinationUrl = Path.Combine(HttpContext.Current.Server.MapPath("~/"), originalUrl);
            destinationUrl = destinationUrl.Replace(Path.GetFileNameWithoutExtension(originalUrl), pictureName);

            if (pictureQuerystringUrl != null)
            {
                var sourceUrl = Path.Combine(HttpContext.Current.Server.MapPath("~/"),
                                             pictureQuerystringUrl.Substring(1));
                ImageBuilder.Current.Build(ImageResizer.Util.PathUtils.RemoveQueryString(sourceUrl), destinationUrl,
                                           new ResizeSettings(sourceUrl));
            }
            
            
        }

    }
    public partial class PictureService
    {
        public string BuildCropedPicture(string queryString,string originalUrl,string type)
        {
            originalUrl = GetOriginalPictureUrl(originalUrl);
            var cropedPictureName = Path.GetFileNameWithoutExtension(originalUrl) + type;
            var savingPath = originalUrl.Replace(Path.GetFileNameWithoutExtension(originalUrl), cropedPictureName);
            SaveCroppedPicture(cropedPictureName, queryString,
                                    originalUrl);

            return savingPath;
            
        }
        
    }
   
    public partial class PictureService
    {
        private static readonly Random Random = new Random((int)DateTime.Now.Ticks);
        private const string FilePath = @"Content/Uploads/Images/";
        private readonly IPictureCommands _pictureCommands;
        private readonly RandomNonceGenerator _randomNonceGenerator;

        public PictureService(IPictureCommands pictureCommands,
            RandomNonceGenerator randomNonceGenerator)
        {
            _pictureCommands = pictureCommands;
            _randomNonceGenerator = randomNonceGenerator;
        }
    }


}
